import dva from 'dva';
import {userDetail, saveUserInfo} from '../services/user';
import {message} from 'antd';

export default {
  namespace: 'user',
  state: {
    loading: true,
    error: ''
  },
  reducers: {
    detail(state, {payload: {data: data}}) {
      return {...state, ...data.data, ...{loading: false}};
    },
    modifyReducer(state, {payload: {data: data}}){
      if (data.code == 201) {
        message.success('保存成功');
        return {...state, ...data.data, ...{error: ''}};
      }
      message.error(data.data.error);
      return {...state, ...{error: data.data.error}};
    }
  },
  effects: {
    *fetch({payload: {id}}, {call, put}) {
      const {data} = yield call(userDetail, {id});
      yield put({type: 'detail', payload: {data: data}});
    },
    *modify({payload: query}, {call, put}){
      const {data} = yield call(saveUserInfo, query);
      yield put({type: 'modifyReducer', payload: {data: data}});
    }
  },
  subscriptions: {
    setup({dispatch, history}) {
      return history.listen(({pathname, query}) => {
        if (pathname === '/user' || pathname === '/usermodify') {
          dispatch({type: 'fetch', payload: query});
        }
      });
    }
  }
};
